package com.free4inno.knowledgems;

import com.free4inno.knowledgems.interceptor.LogInterceptor;
import com.free4inno.knowledgems.interceptor.LoginInterceptor;
import com.free4inno.knowledgems.interceptor.OpenAPIInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Author HUYUZHU.
 * Date 2020/10/15 16:03.
 */
@Configuration
public class KmApplicationConfigurer implements WebMvcConfigurer {
    @Bean
    public HandlerInterceptor getLoginInterceptor() {
        return new LoginInterceptor();
    }

    @Bean
    public HandlerInterceptor getOpenAPIInterceptor() {
        return new OpenAPIInterceptor();
    }

    @Bean
    public HandlerInterceptor getLogInterceptor() {
        return new LogInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getLoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/")
                .excludePathPatterns("/login")
                .excludePathPatterns("/logout")
                .excludePathPatterns("/signup")
                .excludePathPatterns("/resource/**")
                .excludePathPatterns("/search/**")
                .excludePathPatterns("/assets/**")
                .excludePathPatterns("/template/**")
                .excludePathPatterns("/newcss/**")
                .excludePathPatterns("/error/**")
                .excludePathPatterns("/user/getEmail")
                .excludePathPatterns("/uploadfiles/**")
                .excludePathPatterns("/util/downloadImage")
                .excludePathPatterns("/util/downloadAttachment")
                .excludePathPatterns("/bookResource/**")
                .excludePathPatterns("/openapi/**");
        registry.addInterceptor(getOpenAPIInterceptor())
                .addPathPatterns("/openapi/**");
        registry.addInterceptor(getLogInterceptor())
                .addPathPatterns("/**");

    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //当前运行路径
        String runPath = System.getProperty("user.dir");
        //判断操作系统
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win") || os.toLowerCase().startsWith("mac")) {
            registry.addResourceHandler("/uploadfiles/**")
                    .addResourceLocations("file:" + runPath + "\\src\\main\\webapp\\uploadfiles\\");
        } else {
//            registry.addResourceHandler("/uploadImage/**")
//                    .addResourceLocations("file:/usr/local/knowledgems/uploadImage/");
        }
    }
}
